import logging
from flask import request
from info import constants
from flask import current_app,render_template, jsonify
from flask import session
from info.models import User, News, Category
from info.utlis.response_code import RET
from . import index_bp
from info import redis_store
from info import models

@index_bp.route('/')
def index():
    # --------------1.用户帐号和头像显示--------------
    user_id = session.get("user_id")
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)


    # -------2.查询新闻的点击排行数据 -------
    # 1.根据浏览量查询6条点击排行的新闻数据
    try:
        news_model_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news in news_model_list if news_model_list else []:
        news_dict_list.append(news.to_dict())


    # -------3.查询新闻的分类数据 -------
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_dict_list = []
    for category in categories if categories else []:
        category_dict_list.append(category.to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        "news_dict_list": news_dict_list,
        "category_dict_list":category_dict_list
    }

    return render_template("index.html",data=data)

@index_bp.route('/news_list')
def news_list():
    """获取首页新闻列表数据"""
    """
    1.获取参数
        1.1 cid新闻分类id page当前页码（默认值：1） per_page当前页显示新闻的条数(默认值：10)
    2.校验参数
        2.1 非空判断
        2.2 数据的类型判断
    3.逻辑处理
        3.1 根据分类id查询数据，根据新闻的创建时间排序（降序）然后进行分页处理
    4.返回值处理
    """
    #1.获取参数
        #1.1 cid新闻分类id page当前页码（默认值：1） per_page当前页显示新闻的条数(默认值：10)
    params_dict = request.args
    cid = params_dict.get("cid")
    page = params_dict.get("page",1)
    per_page = params_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)
    #2.校验参数
        #2.1 非空判断
    if not all([cid,page,per_page]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
        #2.2 数据的类型判断
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="数据类型错误")
    # 3.逻辑处理
        #3.1 根据分类id查询数据，根据新闻的创建时间排序（降序）然后进行分页处理
    filter = []
    if cid != 1:
        filter.append(News.category_id==cid)

    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc())\
            .paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询首页新闻列表异常")

    if not paginate:
        return jsonify(errno=RET.PARAMERR,errmsg="查询不到该新闻分页")
    # 第cid个分类的所有新闻数据
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_dict_list = []
    for news in items if items else []:
        news_dict_list.append(news.to_dict())
    data = {
        "newsList" :news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }

    return jsonify(errno=RET.OK,errmsg="查询新闻列表数据成功",data=data)





@index_bp.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")
